#!/bin/sh /etc/rc.common
#
# Copyright (C) 2018-2020 xiaoqingfeng(Richard) <xiaoqingfengatgm@gmail.com>.
#

START=13
NAME=homelede-autoconfig

DOCKER_CONFIG="[ -x /etc/init.d/dockerd ] && /etc/init.d/dockerd restart"
CGROUP_MEMORY_CONGIF="echo 1 > /sys/fs/cgroup/memory/memory.use_hierarchy"
SMARTDNS_CONFIG="0 */6 * * * [ -x /etc/init.d/smartdns ] && /etc/init.d/smartdns restart > /dev/null 2>&1 &"
DNSMASQ_CHN_LIST_CONF="0 0 * * * [ -x /etc/init.d/dnsmasq-china-list ] && /etc/dnsmasq-china-list/update.sh > /dev/null 2>&1 &"
start()
{
# Schedule auto reboot for smartdns to bypass secondary dns stop working issue
sed -i '/^.*smartdns.*/d' /etc/crontabs/root >/dev/null 2>&1
if [ -x /etc/init.d/smartdns ]; then
echo "$SMARTDNS_CONFIG" >>/etc/crontabs/root
echo Added smartdns auto restart script.
fi

# Schedule auto update for dnsmasq-china-list
sed -i '/^.*dnsmasq-china-list.*/d' /etc/crontabs/root >/dev/null 2>&1
if [ -x /etc/init.d/dnsmasq-china-list ]; then
echo "$DNSMASQ_CHN_LIST_CONF" >>/etc/crontabs/root
echo Added dnsmasq-china-list auto update script.
fi

# Force dockerd to restart to bypass docker does not create iptable rules issue
#sed -i '/^\[ -x \/etc\/init\.d\/dockerd.*/d' /etc/rc.local >/dev/null 2>&1
if [ -x /etc/init.d/dockerd ]; then
#sed -i '/exit 0/i '"$DOCKER_CONFIG" /etc/rc.local
# set cgroup memory.use_hierarchy to avoid dockerd warning
sed -i '/sys\/fs\/cgroup\/memory\/memory\.use_hierarchy/d' /etc/rc.local
sed -i '/exit 0/i '"$CGROUP_MEMORY_CONGIF" /etc/rc.local
echo Added docker restart script.
fi

# Add ipsec iptable rules to allow ipsec client access router
sed -i '/^.*--pol ipsec.*/d' /etc/firewall.user
 if [ -x /etc/init.d/ipsecvpn ]; then
 echo "iptables -D FORWARD  -m policy --dir in --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user
 echo "iptables -D FORWARD  -m policy --dir out --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user
 echo "iptables -D INPUT -m policy --dir in --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user
 echo "iptables -D OUTPUT -m policy --dir out --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user

 echo "iptables -I FORWARD  -m policy --dir in --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user
 echo "iptables -I FORWARD  -m policy --dir out --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user
 echo "iptables -I INPUT -m policy --dir in --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user
 echo "iptables -I OUTPUT -m policy --dir out --pol ipsec --proto esp -j ACCEPT" >> /etc/firewall.user
fi

# Temporary add scripts for aliddns fix
if [ -r /etc/init.d/aliddns ]; then
	if [ ! -x /etc/init.d/aliddns ]; then
		chmod +x /etc/init.d/aliddns
		chmod +x /usr/sbin/aliddns
	fi
fi

if [ -d /www/luci-static/infinityfreedom ]; then
	if [ ! -r /www/luci-static/infinityfreedom/images/brand.png ]; then
		cp /etc/brand /www/luci-static/infinityfreedom/images/brand.png >/dev/null 2>&1
	fi
fi
}

reload()
{
stop
start
}